package com.gandong8.trace.tool.util;


import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.RecoveryCallback;
import org.springframework.retry.RetryCallback;
import org.springframework.retry.backoff.FixedBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;

import java.util.Collections;
import java.util.concurrent.Callable;

@Slf4j
public class RetryUtil {

    @SuppressWarnings("unchecked")
    public static <T> T run(Callable<T> callable,
                            int retryNum,
                            long sleepTime) throws RuntimeException {
        RetryTemplate retryTemplate = new RetryTemplate();
        SimpleRetryPolicy policy = new SimpleRetryPolicy(retryNum, Collections.singletonMap(Exception.class, true));
        FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
        fixedBackOffPolicy.setBackOffPeriod(sleepTime);
        retryTemplate.setRetryPolicy(policy);
        retryTemplate.setBackOffPolicy(fixedBackOffPolicy);
        final RetryCallback<Object, Exception> retryCallback = context -> callable.call();
        final RecoveryCallback<Object> recoveryCallback = context -> {
            log.info("正在重试:::::::::");
            return null;
        };
        try {
            return (T) retryTemplate.execute(retryCallback, recoveryCallback);
        } catch (Exception e) {
            log.error("重试异常====" + e.getMessage());
            throw new RuntimeException();
        }
    }
}

